﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.Common;
using Oracle.DataAccess.Client;

namespace Petaframe.DataAccess
{
    class StringParameterCommand : IStringParameterCommandBuilder, IDisposable
    {
        private string _commandText;
        private readonly CommandType _cmdType;
        private Func<string, CommandType, int> _callback;
        List< DbParameter> _parameters;
        IDataService _dataService;

        public StringParameterCommand(string command, CommandType cmdType, Func<string, CommandType, int> callback, IDataService dataService)
        {
            _commandText = command;
            _cmdType = cmdType;
            _callback = callback;
            _dataService=dataService;
            _parameters = new List<DbParameter>();            
        }    

        public void Execute()
        {
            AddCommandParameters();
            _callback(_commandText, _cmdType);
        }

        private void AddCommandParameters()
        {
            foreach (DbParameter item in _parameters)
            {
                if (item.Value == null)
                    item.Value = DBNull.Value;

                if (_dataService is IOracleDataService)
                    (_dataService as IOracleDataService).AddInputParameter(item.ParameterName, item.Value, ( item as OracleParameter ).OracleDbTypeEx);
                else
                    _dataService.AddInputParameter(item.ParameterName, item.Value, item.DbType);
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                _callback = null;
                _parameters.Clear();
                _parameters = null;
                _commandText = null;
                if (_dataService != null)
                {
                    _dataService.Dispose();
                    _dataService = null;
                }
            }

        }
        ~StringParameterCommand()
        {
            Dispose(false);
        }

        public List<DbParameter> Parameters
        {
            get
            {
               return _parameters;
            }
           
        }
    }
}
